package com.glory.dgcpcpda.activity.mfg;

import android.os.Build;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.dgcpcpda.R;
import com.glory.dgcpcpda.adapter.ClearMaterielListAdapter;
import com.glory.dgcpcpda.base.BaseActivity;
import com.glory.dgcpcpda.entity.LotInfoEntity;
import com.glory.dgcpcpda.entity.LotList;
import com.glory.dgcpcpda.entity.SimpleEntity;
import com.glory.dgcpcpda.entity.response.BaseResponseBean;
import com.glory.dgcpcpda.utils.LotUtils;
import com.glory.dgcpcpda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * FileName: FTClearMaterielActivity
 * Author: XJH
 * Date: 2020/5/22 10:54
 * Description:FT测试，清料
 * History:
 */
public class FTClearMaterielActivity extends BaseActivity {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.tvEqpMainWork)
    TextView tvEqpMainWork;
    @BindView(R.id.tvEqpItemWork)
    TextView tvEqpItemWork;
    @BindView(R.id.tvNum)
    TextView tvNum;
    @BindView(R.id.list_tv1)
    TextView listTv1;
    @BindView(R.id.list_tv2)
    TextView listTv2;
    @BindView(R.id.list_tv3)
    TextView listTv3;
    @BindView(R.id.list_tv4)
    TextView listTv4;
    @BindView(R.id.rvClearMaterielList)
    RecyclerView rvClearMaterielList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    private ClearMaterielListAdapter mClearMaterielListAdapter;

    private List<LotInfoEntity.LotBean> ftlotlist;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_clear_materiel_ft;
    }

    @Override
    protected void initView() {
        initLayout();
        initEdit(etLot, s -> {
            LotUtils.searchLotInfo(FTClearMaterielActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
                @RequiresApi(api = Build.VERSION_CODES.N)
                @Override
                public void onSuccess(LotInfoEntity response) {
                    tvNum.setText(response.getLOT().getMAINQTY());
                    tvEqpMainWork.setText(response.getLOT().getEQUIPMENTID());
                    ftlotlist = response.getFTLOTLIST();

                    if (ftlotlist != null && ftlotlist.size() > 0) {
                        showPopListView(ftlotlist);
                    }
                    requestData(s);
                }

                @Override
                public void onFail(Throwable t) {

                }
            });
        });
    }

    private void showPopListView(List<LotInfoEntity.LotBean> ftlotlist){
        Collections.sort(ftlotlist, (o1, o2) -> o1.getSTATE().compareTo(o2.getSTATE()));//使用Collections的sort方法，并且重写compare方法

        String context = "可以合并的测试主批:" + "\r\n";
        for (LotInfoEntity.LotBean lot : ftlotlist) {
            if (lot.getUDF().getRESERVED5().equals("")) {
                String Text = lot.getLOTID();
                String state = lot.getSTATE();
                String qty=lot.getMAINQTY();
                if ("正在作业".equals(state)) {
                    Text = Text + " --- " + qty +" --- "+ lot.getLOCATION();
                } else if ("等待作业".equals(state)) {
                    Text = Text + " --- "+ qty + " --- 未进站";
                }
                context = context + Text + "\r\n";
            }
        }

        if(context != ""){
            FreeApi_DialogUtils.getConfirmDialog(FTClearMaterielActivity.this, "确定", context, () -> {

            }).show(getSupportFragmentManager(),"");
        }
    }

    private void requestData(String lotID) {
        FreeUI_EntityCallBack<BaseResponseBean<SimpleEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<SimpleEntity>>
                (new TypeToken<BaseResponseBean<SimpleEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<SimpleEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    SimpleEntity entity = response.body().getResponse().getBody();
                    if (entity.getLISTEQUIPMENT()!=null && entity.getLISTEQUIPMENT().size()>0){
                        tvEqpItemWork.setText(entity.getLISTEQUIPMENT().get(0).getEQUIPMENTID());
                    }
                    if (!entity.getTRACKSHOWMSG().equals("")){
                        showConfirmDialog(entity.getTRACKSHOWMSG());
                    }
                    if (entity.getLOTBINDATALIST().size() <= 0){
                        showToast("暂无BIN数据",false);
                        return;
                    }

                    ArrayList<Double> strings = new ArrayList<>();

                    for(SimpleEntity.MantissaLotBinData entry : entity.getLOTBINDATALIST()){
                        String[] ns = entry.getBINNAME().split("N");
                        String binName = "";
                        if (ns[1].contains("_")){
                            binName = ns[1].replace("_",".");
                        }else{
                            binName = ns[1];
                        }

                        strings.add(Double.parseDouble(binName));
                        entry.setCODE(Double.parseDouble(binName));
                    }
                    Collections.sort(strings);
                    List<SimpleEntity.MantissaLotBinData> simpleEntityList = new ArrayList<>();
                    for (Double s:strings) {
                        for (SimpleEntity.MantissaLotBinData sm:entity.getLOTBINDATALIST()) {
                            if (s == sm.getCODE()){
                                simpleEntityList.add(sm);
                            }
                        }
                    }

                    mClearMaterielListAdapter.setNewData(simpleEntityList);
                }


            }

            @Override
            public void onError(Response<BaseResponseBean<SimpleEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "LOTFTTRACKOUT");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", "SelectClearData");
        map.addProperty("EQUIPMENTID", tvEqpMainWork.getText().toString());
        List<LotList> lotList = new ArrayList<>();
        lotList.add(new LotList(lotID));
        map.add("LOTLIST", new JsonParser().parse(new Gson().toJson(lotList)).getAsJsonArray());
        NetUtils.requestPostNet("CPC.LOTFTTRACKOUT", "LOTFTTRACKOUT", this, map, callBack);
    }

    private void initLayout() {
        listTv1.setText("批号");
        listTv2.setText("BIN名称");
        listTv3.setText("数量");
        listTv4.setText("动作类型");
        tvTitle.setText("结束作业(FT测试-清料)");
        initRecyclerView(rvClearMaterielList,this);
        setMainLayout(llMain);
        mClearMaterielListAdapter = new ClearMaterielListAdapter(null);
        mClearMaterielListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mClearMaterielListAdapter.isFirstOnly(true);
        rvClearMaterielList.setAdapter(mClearMaterielListAdapter);

    }

    @Override
    protected void initData() {
    }

    @OnClick(R.id.tvBaseSubmit)
    public void onViewClicked() {
        if (actionControl("Submit04"))return;
        showSubmitDialog(new onSubmitListener() {
            @Override
            public void setOnSubmitListener() {
                FreeUI_EntityCallBack<BaseResponseBean<SimpleEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<SimpleEntity>>
                        (new TypeToken<BaseResponseBean<SimpleEntity>>() {
                        }.getType(), getSupportFragmentManager(), this) {

                    @Override
                    public void onSuccess(Response<BaseResponseBean<SimpleEntity>> response) {
                        super.onSuccess(response);
                        if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                            String trackshowmsg = response.body().getResponse().getBody().getTRACKSHOWMSG();
                            showConfirmDialog(FTClearMaterielActivity.this,trackshowmsg.equals("") ? "清料成功" : trackshowmsg);
                        }


                    }

                    @Override
                    public void onError(Response<BaseResponseBean<SimpleEntity>> response) {
                        super.onError(response);
                        loadError(response.getException(), "LOTFTTRACKOUT");
                    }
                };
                JsonObject map = new JsonObject();
                map.addProperty("ACTIONTYPE","ClearTrackout");
                map.addProperty("EQUIPMENTID",tvEqpMainWork.getText().toString());
                List<LotList> lotList = new ArrayList<>();
                lotList.add(new LotList(getText(etLot)));
                map.add("LOTLIST", new JsonParser().parse(new Gson().toJson(lotList)).getAsJsonArray());
                List<SimpleEntity.MantissaLotBinData> adapterData = mClearMaterielListAdapter.getData();
                for (SimpleEntity.MantissaLotBinData data : mClearMaterielListAdapter.getData()){
                    switch (data.getCLEARTYPE()){
                        case "留站内":
                            data.setCLEARTYPE("None");
                            break;
                        case "返工":
                            data.setCLEARTYPE("Rework");
                            break;
                        case "报废":
                            data.setCLEARTYPE("Scrap");
                            break;
                        case "分批":
                            data.setCLEARTYPE("Split");
                            break;
                        case "分批出站":
                            data.setCLEARTYPE("SplitTrackOut");
                            break;
                        case "分批报废":
                            data.setCLEARTYPE("SplitScrap");
                            break;
                    }
                }

                map.add("LOTBINDATALIST",new JsonParser().parse(new Gson().toJson(adapterData)).getAsJsonArray());
                NetUtils.requestPostNet("CPC.LOTFTTRACKOUT","LOTFTTRACKOUT",this,map,callBack);
            }
        });
    }

}
